﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Microsoft.VisualStudio.Shell.Interop;
using PowerGuiVsx.Module.Objects;

namespace PowerGuiVsx.Module
{
    [Cmdlet(VerbsData.Initialize, "VsPackage")]
    public class InitializeVsPackageCommand : PowerGuiVsxCommand
    {
        [Parameter(Mandatory = true, ParameterSetName = "Package", ValueFromPipeline = true, Position = 1)]
        public VsPackage VsPackage { get; set; }

        [Parameter(Mandatory = true, ParameterSetName = "Guid", ValueFromPipeline = true, Position = 1)]
        public Guid Guid { get; set; }

        protected override void ProcessRecord()
        {
            if (ParameterSetName.Equals("Package"))
            {
                if (VsPackage == null)
                {
                    WriteError(new ErrorRecord(new ArgumentNullException("VsPackage cannot be null"), String.Empty, ErrorCategory.InvalidArgument, null));
                    return;
                }

                Guid = VsPackage.Id;
            }

            var shell = Package.GetService(typeof(SVsShell)) as IVsShell;
            if (shell == null)
            {
                WriteError(new ErrorRecord(new NullReferenceException("Could not get a reference to IVsShell"), String.Empty, ErrorCategory.InvalidArgument, null));
                return;
            }

            IVsPackage package;
            shell.LoadPackage(Guid, out package);

            if (package == null)
            {
                WriteError(new ErrorRecord(new NullReferenceException(String.Format("Failed to load package [{0}].", Guid)), String.Empty, ErrorCategory.InvalidArgument, null));
            }
        }
    }
}
